package com.cn.longdistancebusstation.scenic.calendar;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.calendar.MultiChooseActivity;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.DatePrice;
import com.cn.longdistancebusstation.model.ListResult;
import com.cn.longdistancebusstation.util.ToolUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.othershe.calendarview.bean.DateBean;
import com.othershe.calendarview.listener.OnPagerChangeListener;
import com.othershe.calendarview.listener.OnSingleChooseListener;
import com.othershe.calendarview.utils.CalendarUtil;
import com.othershe.calendarview.weiget.CalendarView;

import org.xutils.common.util.LogUtil;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by mucheng on 2018/1/26.
 */

public class PriceCalendarActivity extends BaseActivity implements View.OnClickListener{
    private CalendarView mCalendarView;
    private TextView mChooseDateTextView;
    private int[] cDate = CalendarUtil.getCurrentDate();
    private List<DatePrice> mDatePriceslist;
    private String aid;
    private String pid;
    private static Date beginDate;
    private static Date endDate;
    private String cdate;
    private String cprice;
    private String sdate;
    private String currentDate;
    private HashMap<String,String> mPriceMap = new HashMap<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_price_calendar);
        getTitleTextView().setText("日期");
        final TextView title = (TextView) findViewById(R.id.title);
        //当前选中的日期
        mChooseDateTextView = findViewById(R.id.choose_date);
        //
        Intent intent = getIntent();
        aid=intent.getStringExtra("aid");
        pid=intent.getStringExtra("pid");
        String outingDate = intent.getStringExtra("outingDate");
        //
        mCalendarView = (CalendarView) findViewById(R.id.calendar);
        title.setText(cDate[0] + "年" + cDate[1] + "月");
        mChooseDateTextView.setText("当前日期为：" + cDate[0] + "年" + cDate[1] + "月" + cDate[2] + "日");
        Log.d("时间1", mChooseDateTextView +"");
        mCalendarView.setOnPagerChangeListener(new OnPagerChangeListener() {
            @Override
            public void onPagerChanged(int[] date) {
                title.setText(date[0] + "年" + date[1] + "月");
            }
        });

        mCalendarView.setOnSingleChooseListener(new OnSingleChooseListener() {
            @Override
            public void onSingleChoose(View view, DateBean date) {
                title.setText(date.getSolar()[0] + "年" + date.getSolar()[1] + "月");
                mChooseDateTextView.setText(date.getSolar()[0] + "年" + date.getSolar()[1] + "月" + date.getSolar()[2] + "日");
                int year = date.getSolar()[0];
                int month = date.getSolar()[1];
                int day = date.getSolar()[2];
                Intent intent = getIntent();
                String strDate1 = year+"-"+(month<10?"0"+month:month)+"-"+(day<10?"0"+day:day);
                String strDate2 = year+"." + month + "."+ day;
                intent.putExtra("outingDate", strDate1);
                String strPrice = mPriceMap.get(strDate2);
                if(strPrice!=null){
                    strPrice = strPrice.substring(1);
                    intent.putExtra("price", strPrice);
                }else{
                    intent.putExtra("price", "0.00");

                }


                setResult(RESULT_OK, intent);
                finish();
            }
        });
        getAfterDate(20);
        getDatePrices();

    }
    /**
     * 获取前n天日期、后n天日期
     *
     * @param distanceDay 前几天 如获取前7天日期则传-7即可；如果后7天则传7
     * @return
     */
    public static String getAfterDate(int distanceDay) {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        beginDate = new Date();
        Calendar date = Calendar.getInstance();
        date.setTime(beginDate);
        date.set(Calendar.DATE, date.get(Calendar.DATE) + distanceDay);
        endDate = null;
        try {
            endDate = dft.parse(dft.format(date.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        LogUtil.d("第后20天==" + dft.format(endDate));
        return dft.format(endDate);
    }

    private void getDatePrices() {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        currentDate = sdf.format(new Date());
        sdate=sdf.format(endDate);
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<ListResult<DatePrice>> call=httpService.getDatePrice(aid,pid,currentDate,sdate);
        call.enqueue(new Callback<ListResult<DatePrice>>() {
            @Override
            public void onResponse(Call<ListResult<DatePrice>> call, Response<ListResult<DatePrice>> response) {
                ListResult result=response.body();
                if(result!=null){
                    if(result.getHead().getSuccess()){
                        Gson gson=new Gson();
                        String strBody=gson.toJson(result.getBody().getData());
                        Log.d("数据",strBody);
                        Type type=new TypeToken<List<DatePrice>>(){}.getType();
                        mDatePriceslist =gson.fromJson(strBody, type);
                        Log.d("日期价格", String.valueOf(mDatePriceslist.size()));
                        String strDate;
                        String strPrice;
                        String strPriceToyuan;
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.M.d");
                        for(int i=0;i<mDatePriceslist.size();i++){
                            strDate=mDatePriceslist.get(i).getDate();
                            strPrice=("¥"+ ToolUtil.fen2Yuan(mDatePriceslist.get(i).getRetailPrice()));
                            try
                            {
                                strDate = dateFormat.format(sdf.parse(strDate));
                            }
                            catch(ParseException e)
                            {
                            }
                            mPriceMap.put(strDate, strPrice);
                        }
                        mCalendarView
                                .setSpecifyMap(mPriceMap)
                                .setInitDate(cDate[0] + "." + cDate[1])
                                .setSingleDate(cDate[0] + "." + cDate[1] + "." + cDate[2])
                                .init();
//                    mCalendarView.setSpecifyMap(mPriceMap);
                    }else{
                        String strDate;
                        String strPrice="";
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.M.d");
                        mPriceMap.put(String.valueOf(dateFormat), strPrice);
                        mCalendarView
                                .setSpecifyMap(mPriceMap)
                                .setInitDate(cDate[0] + "." + cDate[1])
                                .setSingleDate(cDate[0] + "." + cDate[1] + "." + cDate[2])
                                .init();

                    }

                }else{

                }

            }

            @Override
            public void onFailure(Call<ListResult<DatePrice>> call, Throwable t) {
                Toast.makeText(PriceCalendarActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });



    }



    public void someday(View v) {
        View view = LayoutInflater.from(PriceCalendarActivity.this).inflate(R.layout.input_layout, null);
        final EditText year = (EditText) view.findViewById(R.id.year);
        final EditText month = (EditText) view.findViewById(R.id.month);
        final EditText day = (EditText) view.findViewById(R.id.day);

        new AlertDialog.Builder(this)
                .setView(view)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (TextUtils.isEmpty(year.getText())
                                || TextUtils.isEmpty(month.getText())
                                || TextUtils.isEmpty(day.getText())) {
                            Toast.makeText(PriceCalendarActivity.this, "请完善日期！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        boolean result = mCalendarView.toSpecifyDate(Integer.valueOf(year.getText().toString()),
                                Integer.valueOf(month.getText().toString()),
                                Integer.valueOf(day.getText().toString()));
                        if (!result) {
                            Toast.makeText(PriceCalendarActivity.this, "日期越界！", Toast.LENGTH_SHORT).show();
                        } else {
                            mChooseDateTextView.setText("当前选中的日期为：" + year.getText() + "年" + month.getText() + "月" + day.getText() + "日");
                            Log.d("时间2", mChooseDateTextView +"");
                        }
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    public void today(View view) {
        mCalendarView.today();
        mChooseDateTextView.setText("当前选中的日期为：" + cDate[0] + "年" + cDate[1] + "月" + cDate[2] + "日");
        Log.d("时间3", mChooseDateTextView +"");
    }

    public void lastMonth(View view) {
        mCalendarView.lastMonth();
    }

    public void nextMonth(View view) {
        mCalendarView.nextMonth();
    }

    public void start(View view) {
        mCalendarView.toStart();
    }

    public void end(View view) {
        mCalendarView.toEnd();
    }

    public void lastYear(View view) {
        mCalendarView.lastYear();
    }

    public void nextYear(View view) {
        mCalendarView.nextYear();
    }

    public void multiChoose(View view) {
        startActivity(new Intent(PriceCalendarActivity.this, MultiChooseActivity.class));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
        }

    }

}
